//
//  MainViewController.swift
//  Weibo007
//
//  Created by apple on 15/6/23.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // 获取tabBar
        let tb = MainTabBar()
        setValue(tb, forKeyPath: "tabBar")
        
        tb.compoesButton.addTarget(self, action: "composedButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        addChildViewControllers()
    }
    
    ///  点击撰写按钮，按钮监听方法不能私有
    func composedButtonClicked() {
        print(__FUNCTION__)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // ???
      //  print(tabBar.items)
    }
    
    /// 添加所有的子控制器
    private func addChildViewControllers() {
        let path=NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)!
        let data=NSData(contentsOfFile: path)!
        do
        {
            let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
            for dict in array as! [[String: String]] {
                addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
            }

        }catch
        {
            print(error)
            addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home")
            addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center")
            addChildViewController("DiscoverTableViewController", title: "发现", imageName: "tabbar_discover")
            addChildViewController("ProfileTableViewController", title: "我", imageName: "tabbar_profile")
        }
        
    }
    
    ///  添加控制器
    ///
    ///  :param: vc        子控制器
    ///  :param: title     标题
    ///  :param: imageName 图片名称
    private func addChildViewController(vcName: String, title: String, imageName: String) {
        // 设置 tintColor
        tabBar.tintColor = UIColor.orangeColor()
        let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
        let cls :AnyClass = NSClassFromString(ns + "." + vcName)!
        print(cls)
        let vc = cls.new() as! UIViewController
        print(vc)
        // 从内向外设置，nav & tabbar 都有标题
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted")
        
        let nav = UINavigationController(rootViewController: vc)
        
        addChildViewController(nav)
    }
}
